#-*-coding:utf-8-*-
try:
 import PIL.Image, PIL.ImageDraw, PIL.ImageFont, PIL.ImageEnhance
 import datetime, random,json,math
 import unicodedata,requests,time
 import thread
 from flask import Flask, request, Response,make_response,jsonify
 from flask.ext.responses import json_response
 from cStringIO import StringIO
except ImportError:
    import PIL.Image, PIL.ImageDraw, PIL.ImageFont, PIL.ImageEnhance
dpi=[72,150,180,225,300]
# 生成透明图片,返回图片对象
def transparentImg(size):
     img = PIL.Image.new('RGBA',size, (0, 0, 0, 0))
     draw = PIL.ImageDraw.Draw(img)
     return img
# 将图片缩略贴到透明图片上
def addImgTotransparentImg(img,new_img_path, img_w,img_h,angle,imgPositonX,imgPositonY,isHorizontalFilp=0,isVerticalFilp=0):
    # 需要贴的图片
    new_img=PIL.Image.open(new_img_path).convert('RGBA')
    new_img = new_img.resize((img_w, img_h), PIL.Image.NEAREST)
    if (isHorizontalFilp == 1):
        new_img = new_img.transpose(PIL.Image.FLIP_LEFT_RIGHT)
    if (isVerticalFilp == 1):
        new_img = new_img.transpose(PIL.Image.FLIP_TOP_BOTTOM)
    #缩略图对角线长度
    new_img_z=int(math.sqrt(new_img.size[0]*new_img.size[0]+new_img.size[1]*new_img.size[1]))
    # 贴图底图计算大小
    watermark = PIL.Image.new('RGBA',(new_img_z,new_img_z), (0, 0, 0, 0))
    # 在水印底图中心
    watermark.paste(new_img,(int((new_img_z-new_img.size[0])/2),int((new_img_z-new_img.size[1])/2)))
    # 旋转
    watermark = watermark.rotate(angle,PIL.Image.BICUBIC)
    # 贴图区域，以旋转中心为中心
    watermark_crop_x0=int(imgPositonX-watermark.size[0]/2)
    watermark_crop_y0=int(imgPositonY-watermark.size[1]/2)
    crop_x0=0
    crop_y0=0
    # 贴图宽小于中心中心点坐标
    if (watermark_crop_x0<0):
        crop_x0=-watermark_crop_x0
        watermark_crop_x0 = 0
    if (watermark_crop_y0<0):
        crop_y0=-watermark_crop_y0
        watermark_crop_y0 = 0
    watermark_crop_x1=int(imgPositonX+watermark.size[0]/2)
    watermark_crop_y1=int(imgPositonY+watermark.size[1]/2)
    crop_x1=watermark.size[0]
    crop_y1=watermark.size[1]
    # 图片在区域内
    if (watermark_crop_x1>img.size[0]):
        watermark_crop_x1=img.size[0]
        crop_x1=crop_x0+img.size[0]-watermark_crop_x0
    else:
        watermark_crop_x1=crop_x1-crop_x0+watermark_crop_x0
    if (watermark_crop_y1>img.size[1]):
        watermark_crop_y1=img.size[1]
        crop_y1=crop_y0+img.size[1]-watermark_crop_y0
    else:
        watermark_crop_y1 = crop_y1 - crop_y0 + watermark_crop_y0
    watermark=watermark.crop((crop_x0,crop_y0,crop_x1,crop_y1))
    # #贴水印图片，有可能超出底图范围，需要将需要部分复制下来再贴上去
    img.paste(watermark, (watermark_crop_x0, watermark_crop_y0,watermark_crop_x1, watermark_crop_y1), watermark)
#     时间戳+随机数生成图片文件名
def generateUnique():
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
    randomNum = random.randint(1000, 10000)  # 生成的随机整数n
    return str(nowTime) + str(randomNum)
def text_watermark(img,text, angle, opacity,FONT,size,fillcolour,(imgPositonX,imgPositonY)):
    n_font = PIL.ImageFont.truetype(FONT, size)                                       #得到字体
    n_width, n_height = n_font.getsize(text)
    n_max_l=max(n_width,n_height)
    watermark = PIL.Image.new('RGBA',(n_max_l,n_max_l), (0,0,0,0)) #我这里有一层白色的膜，去掉(255,255,255) 这个参数就好了
    draw = PIL.ImageDraw.Draw(watermark, 'RGBA')
    draw.text((int((n_max_l-n_width)/2),int((n_max_l-n_height)/2)),
              text, font=n_font, fill=fillcolour)
    # draw.text((0,0),text, font=n_font, fill=fillcolour)
    watermark = watermark.rotate(angle, PIL.Image.BICUBIC)
    alpha = watermark.split()[3]
    alpha = PIL.ImageEnhance.Brightness(alpha).enhance(opacity)
    watermark.putalpha(alpha)
    # 贴图区域，以旋转中心为中心
    watermark_crop_x0=int(imgPositonX-watermark.size[0]/2)
    watermark_crop_y0=int(imgPositonY-watermark.size[1]/2)
    crop_x0=0
    crop_y0=0
    # 贴图宽小于中心中心点坐标
    if (watermark_crop_x0<0):
        crop_x0=-watermark_crop_x0
        watermark_crop_x0 = 0
    if (watermark_crop_y0<0):
        crop_y0=-watermark_crop_y0
        watermark_crop_y0 = 0
    watermark_crop_x1=int(imgPositonX+watermark.size[0]/2)
    watermark_crop_y1=int(imgPositonY+watermark.size[1]/2)
    crop_x1=watermark.size[0]
    crop_y1=watermark.size[1]
    # 图片在区域内
    if (watermark_crop_x1>img.size[0]):
        watermark_crop_x1=img.size[0]
        crop_x1=crop_x0+img.size[0]-watermark_crop_x0
    else:
        watermark_crop_x1=crop_x1-crop_x0+watermark_crop_x0
    if (watermark_crop_y1>img.size[1]):
        watermark_crop_y1=img.size[1]
        crop_y1=crop_y0+img.size[1]-watermark_crop_y0
    else:
        watermark_crop_y1 = crop_y1 - crop_y0 + watermark_crop_y0
    watermark=watermark.crop((crop_x0,crop_y0,crop_x1,crop_y1))
    watermark=watermark.resize((crop_x1-crop_x0,crop_y1-crop_y0),PIL.Image.NEAREST)
    # #贴水印图片，有可能超出底图范围，需要将需要部分复制下来再贴上去
    img.paste(watermark, (watermark_crop_x0, watermark_crop_y0,watermark_crop_x1, watermark_crop_y1), watermark)
app = Flask(__name__)
app.debug = True
@app.route('/createImg', methods=['POST','GET'])
def createImg():
  #底图，透明背景大小，如果没有参数，默认5000*5000
  # 放大倍数
  start = time.clock()
  img_parms=request.json['image_parm_arr']
  img = transparentImg((int(request.json['boxW']),int(request.json['boxH'])))
  # dpi=int(request.json['dpi'])
  dpi=180
  savePath=request.json['save_path']
  for index,img_parm in enumerate(img_parms):
      multiple = img_parm.get('multiple')
      if(img_parm.get('type')==1):
       img_path =unicodedata.normalize('NFKD',img_parm.get('img_path')).encode('ascii','ignore')
       img_w    =img_parm.get('imgW')
       img_h    =img_parm.get('imgH')
       img_angle=img_parm.get('angle')
       imgPositonX=int(img_parm.get('imgPositonX'))
       imgPositonY=int(img_parm.get('imgPositonY'))
       isHorizontalFilp = int(img_parm.get('isHorizontalFilp'))
       isVerticalFilp = int(img_parm.get('isVerticalFilp'))
       addImgTotransparentImg(img,img_path, img_w,img_h,img_angle,imgPositonX,imgPositonY,isHorizontalFilp,isVerticalFilp)
      if(img_parm.get('type')==2):
        fontpath = img_parm.get('font_path')
        fontAngle = img_parm.get('angle')
        imgPositonX = int(img_parm.get('imgPositonX'))
        imgPositonY = int(img_parm.get('imgPositonY'))
        text = img_parm.get('text')
        size=img_parm.get('font_size')
        fillcolour=img_parm.get('font_color')
        text_watermark(img,text, fontAngle, 1,fontpath,size,fillcolour,(imgPositonX,imgPositonY))
  img.save(savePath,'PNG',dpi=(dpi,dpi))
  # img.show()
  return  make_response(jsonify( {"code":1,"msg":'success '}), 200)
if __name__ == '__main__':
  # port=5000 端口号
  app.run(port=9999)